package com.huibur.devicecheck.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huibur.devicecheck.enums.TaskEnums;
import com.huibur.devicecheck.enums.TaskStatusEnums;
import com.huibur.devicecheck.mapper.TaskMapper;
import com.huibur.devicecheck.model.po.TaskPO;
import com.huibur.devicecheck.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/*******************************************************
* @title: SaticScheduleTask.java
* @description: 定时任务
* @author wushiqi
* @date 2021/10/8
* @version 1.0
*******************************************************/
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {

    @Autowired
    TaskMapper taskMapper;

    //3.添加定时任务
    //每月1号凌晨1点执行一次：0 0 1 1 * ?
    //每隔1分钟执行一次：0 */1 * * * ?  （用于测试）
    @Scheduled(cron = "0 0 1 1 * ?")
    private void configureTasks() throws ParseException {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());

        Calendar cal = Calendar.getInstance();
        //获取月份
        int month = cal.get(Calendar.MONTH) + 1;
        //获取年份
        int year = cal.get(Calendar.YEAR);
        //获取当前月最后一天的最后一分最后一秒
        String lastDayOfMonth = SaticScheduleTask.getLastDayOfMonth(month);

        //将之前的任务的状态修改成结束状态。
        TaskPO taskPO = new TaskPO();
        TaskPO task = taskMapper.selectOne(new LambdaQueryWrapper<TaskPO>()
                .eq(TaskPO::getIsDeleted, TaskEnums.NORMAL.getCode())
                .eq(TaskPO::getStatus, TaskStatusEnums.IN_PROGRESS.getCode()));
        taskPO.setId(task.getId());
        taskPO.setStatus(TaskStatusEnums.HAS_ENDED.getCode());
        taskMapper.updateById(taskPO);

        TaskPO newTask = new TaskPO();
        //每个月生成定时任务
        newTask.setTitle(month + "月巡检任务（" + year + ")");
        newTask.setIsDeleted(TaskEnums.NORMAL.getCode());
        newTask.setPlanStartTime(DateUtils.getCurrentTimestamp());
        newTask.setPlanEndTime(Timestamp.valueOf(lastDayOfMonth));
        newTask.setCreateAt(DateUtils.getCurrentTimestamp());
        newTask.setStatus(TaskStatusEnums.IN_PROGRESS.getCode());
        newTask.setDescription("这是" + month + "月巡检任务（" + year + ")");
        taskMapper.insert(newTask);
    }

    //获取当前月最后一天：
    public static String getLastDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int maxDay = 0;
        //2月的平年瑞年天数
        if(month==2) {
            maxDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);
        }else {
            maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        // 设置日历中月份的最大天数
        calendar.set(Calendar.DAY_OF_MONTH, maxDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDay = sdf.format(calendar.getTime())+" 23:59:59";

        return lastDay;
    }

}
